import {HTTP} from "../../../utils/http.js";
import Dialog from '../../../miniprogram_npm/vant-weapp/dialog/dialog';
var http = new HTTP();
import { ActModel } from "../../../models/ActModel.js"
const _ActModel = new ActModel();

const app = getApp();
var that;
Page({
  data: {
    type:"new",
    btnOpTitle:"保存",
    actId:"",
    actTitle:"",
    actAddr:"",
    region: ['北京市', '北京市', '朝阳区'],
    customItem: '全部',
    actDate: "", 
    duration:"1",
    actContent:"",
    startDate:"",
    endDate:"",
    actTime:"12:00",
    images: [],
    imageWidth: 120,
    person_limit:50
  },
  actTitleChange:function(e){
    this.setData({
      actTitle:e.detail.value
    })
  },
  actAddrChange:function(e){
    this.setData({
      actAddr: e.detail.value
    })
  },
  initImageWidth:function(){
    that.setData({
      imageWidth: Math.floor((app.globalData.windowWidth - 40 - 18) / 3)
    });
  },
  onLoad: function (options) {
  
    that = this;
    let startDate = this.getStartDate();
    let endDate = this.getEndDate();
    console.log(startDate, endDate)
    this.setData({
      actDate:startDate,
      startDate: startDate,
      endDate:endDate
    })
   
    this.initImageWidth();
    if (options.type=='edit' && options.actId) {
     
      that.setData({
        type:options.type,
        actId:options.actId,
        btnOpTitle:"更新"
      })

      _ActModel.getDetail(options.actId, function (data) {
        let item = data[0]
        that.setData({
          person_limit:item.personLimit,
          startDate:item.startDate,
          startTime:item.startTime,
          actTitle:item.title,
          duration: item.duration,
          actContent:item.content,
          actAddr: item.addr,
          region: item.city.split(',')
        })
        console.log(that.data.region)
        var imageArr = [];
        item.activityImgList.forEach(function (value, index){
            imageArr.push(value.filePath);
        });
        if(imageArr.length>0){
          wx.downloadFile({
            url: imageArr[0],
            success: function (res) {
              if (res.statusCode === 200) {
                console.log('图片下载成功' + res.tempFilePath)
               
                const fs = wx.getFileSystemManager()
                fs.saveFile({
                  tempFilePath: res.tempFilePath, // 传入一个临时文件路径
                  success(res) {
                    let images = [];
                    images.push(res.savedFilePath);
                    that.setData({
                      images: images
                    })
                  
                  }
                })
              } else {
                console.log('响应失败', res.statusCode)
              }
            }
          });
        
        }
      });
    }
  },
  getStartDate:function(){
    var myDate = new Date();
    var year = myDate.getFullYear();   
    var month = myDate.getMonth() + 1;     
    var day = myDate.getDate();   
    if (month >= 1 && month <= 9) {
     month = "0" + month;
    }
    //获取完整年月日
    return  year + "-" + month + "-" + day;
  },
  getEndDate:function(){
    var myDate = new Date();
    var year = myDate.getFullYear();    
    var month = myDate.getMonth() + 1; 
    var day = myDate.getDate();  
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }  
    //获取完整年月日
    return (parseInt(year) + 2) + "-" + month + "-" + day;
  }
  ,
  onShow: function () {

  },
  bindTimeChange:function(e){
    this.setData({
      actTime:e.detail.value
    })
  },
  bindRegionChange:function(e){
    this.setData({
      region: e.detail.value
    })
  },
  bindDateChange: function (e) { 
    this.setData({
      actDate: e.detail.value
    })
  },
  chooseImage: function () {
    // 选择图片
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        let len = tempFilePaths.length;

        let imagesLen = that.data.images.length
        if (imagesLen + len <= 9) {
          that.setData({
            images: that.data.images.concat(tempFilePaths)
          });
        } else {
          var subtag = (9 - that.data.images.length);

          that.setData({
            images: that.data.images.concat(tempFilePaths.slice(0, subtag))
          });
        }

      }
    })
  },
  previewImage: function () {
    // 预览图集
    wx.previewImage({
      urls: that.data.images
    });
  },
  formSubmit:function(e){
    var _self = this;
    let actContent = e.detail.value.actContent;
    let personLimit = e.detail.value.person_limit;
    // this.setData({
    //   actContent:actContent
    // });
    let location = this.data.region.join(",");

    if(this.data.actTitle==""){
      Dialog.alert({
        title: '提示',
        message: "请输入活动标题。"
      });
      return;
    }
    if (location == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动城市。"
      });
      return;
    }

    if (this.data.actAddr == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动地点。"
      });
      return;
    }

    if (this.data.actDate == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动日期。"
      });
      return;
    }
    if (this.data.actTime == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动日期。"
      });
      return;
    }
    if (this.data.duration == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动时长。"
      });
      return;
    }

    if (this.data.duration == "") {
      Dialog.alert({
        title: '提示',
        message: "请输入活动内容描述。"
      });
      return;
    }

    if (this.data.images.length<=0) {
      Dialog.alert({
        title: '提示',
        message: "请至少上传一张图片。"
      });
      return;
    }

    let data = 
    {
      "title":this.data.actTitle,
      "city": location,
      "addr":this.data.actAddr,
      "startDate": this.data.actDate,
      "startTime": this.data.actTime,
      "duration": this.data.duration,
      "content": actContent,
      "personLimit": personLimit
    }
   
    http.uploadImages(this.data.images, function (images) {
      // data.actImgs = images.join(",");
      data.actImgs = images;
      console.log("图片上传成功", data);
      if(_self.data.type=='edit'){
        data.id = _self.data.actId;
        _ActModel.update(data,function(data){
          Dialog.alert({
            message: '更新成功'
          }).then(() => {
            var pages = getCurrentPages();
            if (pages.length > 1) {
              var prePage = pages[pages.length - 2];
              prePage.changeData();
              wx.navigateBack();
            }
          });
        })
      }else{
        _self.publishActivity(data)
      }
      
    });


  },
  publishActivity: function (data) {
    http.request({
      url: "/act/build",
      method: "POST",
      data: data,
      success: function (res) {
        console.log(res);

        Dialog.alert({
          message: '发布成功'
        }).then(() => {
          var pages = getCurrentPages();
          if (pages.length > 1) {
            var prePage = pages[pages.length - 2];
            //关键在这里
            //prePage.changeData();
            wx.navigateBack();
          }
        });

      }
    })
  }
})